package org.example.dingtalkintegrationservice.service;

import jakarta.annotation.Resource;
import org.example.dingtalkintegrationservice.pojo.IdRecord;
import org.example.dingtalkintegrationservice.exception.ResourceNotFoundException;
import org.example.dingtalkintegrationservice.repository.IdRecordRepository;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Optional;

/**
 * @author pc
 */
@Service
public class IdRecordService {
    @Resource
    IdRecordRepository idRecordRepository;
    public String getId2ById1(String id1){
        Optional<IdRecord> res = idRecordRepository.findLatestById1(id1);
        if (res.isPresent()){
            return res.get().getId2();
        }
        else {
         throw new ResourceNotFoundException("id1:%s is not exist".formatted(id1));
        }
    }
    public String getParentById1(String id1){
        Optional<IdRecord> res = idRecordRepository.findLatestById1(id1);
        if (res.isPresent()){
            return res.get().getParentId();
        }
        else {
            throw new ResourceNotFoundException("id1:%s is not exist".formatted(id1));
        }
    }
    public String getId2ById1AndUserId(String id1,String userId){
        Optional<IdRecord> res = idRecordRepository.findLatestById1AndUserId(id1,userId);
        if (res.isPresent()){
            return res.get().getId2();
        }
        else {
            throw new ResourceNotFoundException("id1:%s is not exist".formatted(id1));
        }
    }
    public void insertIdRecordBatch(List<IdRecord> idRecordList){
        idRecordRepository.saveAll(idRecordList);
    }
}
